<template>
  <div style="display:flex;">
    <el-input
      ref="valueDom"
      @focus="handleFocus"
      v-if="textVisible"
      :value="text"
      :disabled="disabled"
      placeholder=""
      v-popover:popover
    >
      <i slot="suffix" style="margin-right:5px" @click="handleFocus" class="el-icon-search"></i>
    </el-input>
    <el-input
      ref="filterDom"
      v-else
      v-popover:popover
      v-model="filter"
      :disabled="disabled"
      placeholder="请输入筛选内容"
      @keyup.enter.native="handleEnterPress"
      @keyup.esc.native="handleBlur"
      @blur="handleBlur"
    >
      <i slot="suffix" style="margin-right:5px" class="el-icon-edit"></i>
    </el-input>
    <el-popover
      ref="popover"
      :disabled="disabled"
      @show="handlePopoverShow"
      trigger="manual"
      :value="!textVisible"
    >
      <!--:value="!textVisible"-->
      <el-table
        :data="cpFilterRows"
        :size="propSize || 'medium'"
        :style="propStyle"
        :height="propHeight || 250"
        :stripe="propStripe"
        :row-class-name="getRowClass"
        @row-click="handleSelect"
      >
        <el-table-column
          type="index"
          width="80"
          align="center"
        />
        <el-table-column
          v-for="col in columns"
          :key="col[propValueField]"
          :width="col.width"
          :label="col.label || col.name"
          :prop="col.name"
          align="center"
        />
      </el-table>
    </el-popover>
  </div>
</template>
<script>
export default {
  data() {
    return {
      textVisible: true,
      popVisible: false,
      disabled: false,
      filter: '',
      text: '',
      popperClass: this.propPopperClass,
      rows: this.propRows,
      filterRows: this.propRows,
      columns: this.propColumns,
      unitFetchCondition: '',
    }
  },
  model: {

  },
  props: {
    propTextField: {
      type: String,
      default: 'unit'
    },
    propValueField: {
      type: [String, Number],
      default: 'id'
    },
    propText: {
      type: String
    },
    propColumns: {
      type: Array,
      required: false,
      default: () =>  [
        { label: '包装单位', name: 'unit', width: 200, search: true },
        { label: '包装比率',  name: 'rate', width: 150, search: false },
        { label: '单价(元)',  name: 'price', search: false },
      ]
    },
    propRows: {
      type: Array,
      // required: true,
      default: () => []
    },
    propUrl: {
      type: String
    },
    value: {
      type: String
    },
    propSize: {
      type: String
    },
    propHeight: {
      type: [String, Number],
      default: () => '20vh'
    },
    propStyle: {
      type: String,
      default: () => 'width: 30vw'
    },
    propStripe: {
      type: Boolean
    },
    propDisabled: {
      type: Boolean,
      default: () => false
    },
    propMatrId: {
      type: String,
      default: () => ''
    },
    propPurchase: {
      // 采购单位
      type: Boolean,
      default: () => null
    },
    propApply: {
      // 请领单位
      type: Boolean,
      default: () => null
    },
  },
  watch: {
    propRows(values) {
      this.rows = values
      this.filterRows = values
    },
    value(newVal) {
      if (!newVal) {
        this.text = ''
      } else {
        this.text = this.getTextByValue(newVal)
      }
      if (this.strings.isBlank(this.text)) {
        this.text = this.propText
      }
    },
    filter(newVal) {
      this.filterRows = this.strings.isNotBlank(newVal) ? this.rows.filter(this.createFilter(newVal)) : this.rows
    },
    'propDisabled': {
      handler(newVal) {
        this.disabled = newVal
      },
      deep: true,
      immediate: true,
    }
  },
  created() {
    // this.fetchData()
  },
  mounted() {
    let {propMatrId, textVisible} = this

    this.unitFetchCondition = JSON.stringify({
      propMatrId
    })
    this.fetchData()
  },
  computed: {
    cpFilterRows() {
      return this.filterRows ? this.filterRows.filter((row, index) => index < 50) : []
    }
  },
  components: {
  },
  methods: {
    isSelected(item) {
      return item[this.propValueField] == this.value
    },
    isFirst(item) {
      return this.filterRows && this.filterRows[0] && this.filterRows[0][this.propValueField] == item[this.propValueField]
    },
    getTextByValue(val) {
      const item = this.rows.find(row => {
        return row[this.propValueField] == val
      })
      if (item) {
        return item[this.propTextField]
      } else {
        return ''
      }
    },
    getCurrentRow() {
      return this.propRows.filter(row => row[this.propValueField] == this.value)[0]
    },
    createFilter(queryString) {
      return (item) => {
        let found = false
        this.columns.forEach(col => {
          if (col.search && item[col.name].toLowerCase().indexOf(queryString.toLowerCase()) > -1) {
            found = true
            return true
          }
        })
        return found
      }
    },
    handleSelect(item) {
      if (item.forbidden) {
        return
      }
      // 关闭popover
      document.querySelector('#app') && document.querySelector('#app').click()

      this.textVisible = true
      this.text = item[this.propTextField]
      this.$emit('input', item[this.propValueField])
      this.$emit('select', item)
    },
    handleEnterPress() {
      // if (this.filterRows && this.filterRows.length > 0) {
      //   this.handleSelect(this.filterRows[0])
      // } else {
      //   this.handleBlur()
      // }
    },
    handleBlur() {
      if (this.cpFilterRows && this.cpFilterRows.length > 0) {
        let item = this.cpFilterRows[0]
        this.handleSelect(item)
      }
      // setTimeout(() => {
      //   this.filter = ''
      //   this.textVisible = true
      //   // 防止输入框获得光标乱改数据
      //   this.$nextTick(() => {
      //     this.$refs.valueDom && this.$refs.valueDom.blur()
      //   })
      // }, 100)
    },
    getRowClass(para) {
      const fun = this.$listeners['row-class']
      if (fun) {
        return fun(para)
      }
    },
    handleFocus() {
      this.textVisible = false
      this.$nextTick(() => {
        this.$refs.filterDom.focus()
        this.popVisible = true
      })
    },
    handleNodeClick(data) {
      let {value} = data

      let filterRows = this.filter ? this.rows.filter(this.createFilter(this.filter)) : this.rows
      this.filterRows = filterRows.filter(row => {
        return this.strings.isBlank(value) ? true : row.flagOmoc == value
      })
    },
    async handlePopoverShow() {
      // 显示pop over弹窗时，判断条件是否已更改，如果时，需要重新加载
      let {propMatrId, textVisible} = this

      let unitFetchCondition = JSON.stringify({
        propMatrId
      })

      if (unitFetchCondition == this.unitFetchCondition) {
        this.filterRows = this.rows
        return
      }
      await this.fetchData()
      this.filterRows = this.rows
      this.unitFetchCondition = unitFetchCondition
    },
    async fetchData() {
      if (this.strings.isBlank(this.propUrl)) {
        return
      }
      if (this.strings.isBlank(this.propMatrId)) {
        return
      }

      let wrapper = this.$newWrapper()
        .eq('matrId', this.propMatrId)
      if (this.propPurchase != null) {
        wrapper.eq('flagPurchase', this.propPurchase)
      }
      if (this.propApply != null) {
        wrapper.eq('flagApply', this.propApply)
      }
      let params = {
        queryString: JSON.stringify(wrapper.queryConditions)
      }
      let resp = await this.$ajax.get(this.propUrl, {params})
      this.rows = resp.data
      this.filterRows = this.rows
    },
    handlerVisible() {
      this.textVisible = true
    }
  }
}
</script>
<style lang="scss" scoped>

</style>
